import React, { useState, useRef, useCallback, useEffect } from 'react'
import { Upload, Trash2, FileSearch } from 'lucide-react'
import { useComplianceStore } from '@/stores/useComplianceStore'
import { showMessage } from '@/components/common/MessageTip'
import { getAttachmentFile, copyExistingAttachments } from '@/api/work'
import { AxiosError } from 'axios'
import DeleteConfirmModal from '@/components/common/DeleteConfirmModal'
import { getBaseURL } from '@/utils/utils'
import ProgressBar from '@/components/common/ProgressBar'
import ExistingAttachmentSelector from './ExistingAttachmentSelector'
import type { Attachment } from '@/types/work'

interface FileUploadSectionProps {
  attachments: Attachment[]
  onAttachmentsChange: (attachments: Attachment[]) => void
  onFileRename: (file: File) => void
  complianceItemId: string
  renamedFileToUpload?: File | null // 新增：需要上传的重命名文件
  onRenamedFileUploaded?: () => void // 新增：重命名文件上传完成回调
  assessmentPlanId?: string // 新增：评估计划ID，用于选择已有附件
}

const FileUploadSection: React.FC<FileUploadSectionProps> = ({
  attachments,
  onAttachmentsChange,
  onFileRename,
  complianceItemId,
  renamedFileToUpload,
  onRenamedFileUploaded,
  assessmentPlanId
}) => {
  const { uploadFile, removeFile } = useComplianceStore()
  const [isDragging, setIsDragging] = useState(false)
  const [fileInputKey, setFileInputKey] = useState(Date.now())
  const fileInputRef = useRef<HTMLInputElement>(null)
  const MAX_ATTACHMENTS = 10

  // 删除文件相关状态
  const [fileToDelete, setFileToDelete] = useState<string | null>(null)
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
  const [fileToDeleteName, setFileToDeleteName] = useState('')

  // 上传中的临时队列（不确定态展示）
  const [uploadingItems, setUploadingItems] = useState<Array<{ id: string; name: string }>>([])

  // 已有附件选择器状态
  const [isAttachmentSelectorOpen, setIsAttachmentSelectorOpen] = useState(false)

  // 文件上传处理
  const handleFileUpload = useCallback(async (files: FileList | File[]) => {
    const fileArray = Array.from(files)
    
    // 检查文件数量限制（包含正在上传的数量）
    const remainingSlots = Math.max(0, MAX_ATTACHMENTS - attachments.length - uploadingItems.length)
    if (fileArray.length > remainingSlots) {
      showMessage('warning', `最多只能上传${MAX_ATTACHMENTS}个文件`, {
        position: 'top-right',
        autoClose: 3000
      })
      return
    }

    const filesToUpload = fileArray.slice(0, remainingSlots)
    const newAttachments: Attachment[] = []

    try {
      // 上传所有文件
      for (const file of filesToUpload) {
        const tempId = `${Date.now()}-${Math.random()}`
        // 加入上传队列（显示不确定态）
        setUploadingItems(prev => [...prev, { id: tempId, name: file.name }])
        try {
          const attachment = await uploadFile(complianceItemId!, file)
          newAttachments.push(attachment)
        } finally {
          await new Promise(resolve => setTimeout(resolve, 500))
          // 无论成功失败都移除该条上传任务
          setUploadingItems(prev => prev.filter(item => item.id !== tempId))
        }
      }
      
      // 更新附件列表
      onAttachmentsChange([...attachments, ...newAttachments])
      
      showMessage('success', '文件上传成功', {
        position: 'top-right',
        autoClose: 3000
      })
      setFileInputKey(Date.now())
      
    } catch (error) {
      console.error('文件上传失败:', error)
      const errorMessage = error instanceof AxiosError 
        ? error.message || '文件上传失败'
        : '文件上传失败'
        
      showMessage('error', errorMessage, {
        position: 'top-right',
        autoClose: 3000
      })
    }
  }, [attachments, complianceItemId, uploadFile, onAttachmentsChange, uploadingItems.length])

  // 拖拽事件处理
  const handleDragOver = useCallback((e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault()
    e.stopPropagation()
    if (!isDragging) setIsDragging(true)
  }, [isDragging])

  const handleDragLeave = useCallback((e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault()
    e.stopPropagation()
    setIsDragging(false)
  }, [])

  const handleDrop = useCallback((e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault()
    e.stopPropagation()
    setIsDragging(false)
    
    const { files } = e.dataTransfer
    if (files && files.length > 0) {
      handleFileUpload(files)
    }
  }, [handleFileUpload])

  // 粘贴事件处理
  useEffect(() => {
    const handlePaste = (e: ClipboardEvent) => {
      const items = e.clipboardData?.items
      if (!items) return

      const filesToProcess: File[] = []
      const filesToRename: File[] = []

      // 分类文件：需要重命名的和不需要的
      for (let i = 0; i < items.length; i++) {
        const item = items[i]
        
        if (item.kind === 'file') {
          const file = item.getAsFile()
          
          if (file) {
            // 检查是否为需要重命名的图片
            if (file.name === '图片.png' || file.name === 'image.png') {
              filesToRename.push(file)
            } else {
              filesToProcess.push(file)
            }
          }
        }
      }

      // 如果有文件需要处理
      if (filesToProcess.length > 0 || filesToRename.length > 0) {
        e.preventDefault()
        
        // 立即上传不需要重命名的文件
        if (filesToProcess.length > 0) {
          handleFileUpload(filesToProcess)
        }
        
        // 处理需要重命名的文件
        if (filesToRename.length > 0) {
          onFileRename(filesToRename[0])
        }
      }
    }
    
    document.addEventListener('paste', handlePaste)
    return () => {
      document.removeEventListener('paste', handlePaste)
    }
  }, [handleFileUpload, onFileRename])

  // 使用 ref 跟踪已处理的重命名文件，避免重复上传
  const processedRenamedFileRef = useRef<File | null>(null)

  // 处理重命名文件上传
  useEffect(() => {
    if (renamedFileToUpload && complianceItemId && renamedFileToUpload !== processedRenamedFileRef.current) {
      processedRenamedFileRef.current = renamedFileToUpload
      
      // 直接调用上传逻辑，避免依赖handleFileUpload导致的重复执行
      const uploadRenamedFile = async () => {
        let tempId: string | null = null
        try {
          tempId = `${Date.now()}-${Math.random()}`
          // 进入上传队列
          setUploadingItems(prev => [...prev, { id: tempId as string, name: renamedFileToUpload.name }])
          const attachment = await uploadFile(complianceItemId, renamedFileToUpload)
          onAttachmentsChange([...attachments, attachment])
          showMessage('success', '文件上传成功', {
            position: 'top-right',
            autoClose: 3000
          })
          onRenamedFileUploaded?.()
        } catch (error) {
          console.error('文件上传失败:', error)
          const errorMessage = error instanceof AxiosError 
            ? error.message || '文件上传失败'
            : '文件上传失败'
          showMessage('error', errorMessage, {
            position: 'top-right',
            autoClose: 3000
          })
        } finally {
          // 移除上传队列项（按临时ID过滤，避免并发错删）
          if (tempId) {
            setUploadingItems(prev => prev.filter(item => item.id !== tempId))
          }
        }
      }
      uploadRenamedFile()
    }
    
    // 清理已处理的文件引用
    if (!renamedFileToUpload) {
      processedRenamedFileRef.current = null
    }
  }, [renamedFileToUpload, complianceItemId, uploadFile, attachments, onAttachmentsChange, onRenamedFileUploaded])

  // 文件输入处理
  const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      handleFileUpload(e.target.files)
      e.target.value = ''
    }
  }

  const triggerFileInput = () => {
    fileInputRef.current?.click()
  }

  // 文件点击处理（预览/下载）
  const handleFileClick = async (file: { id: string; type: string; name: string }) => {
    try {
      const blob = await getAttachmentFile(file.id)
      const url = URL.createObjectURL(blob)
      
      if (file.type && file.type.startsWith('image/')) {
        window.open(url, '_blank', 'noopener,noreferrer')
      } else {
        const link = document.createElement('a')
        link.href = url
        link.download = file.name
        document.body.appendChild(link)
        link.click()
        link.remove()
      }
      setTimeout(() => URL.revokeObjectURL(url), 1000)
    } catch (error) {
      console.error('获取文件失败:', error)
      showMessage('error', '文件获取失败', {
        position: 'top-right',
        autoClose: 3000
      })
    }
  }

  // 删除文件处理
  const handleRemoveFile = (fileId: string, fileName: string) => {
    setFileToDelete(fileId)
    setFileToDeleteName(fileName)
    setIsDeleteModalOpen(true)
  }

  const confirmDeleteFile = async () => {
    if (!fileToDelete) return
    
    try {
      await removeFile(fileToDelete)
      onAttachmentsChange(attachments.filter(a => a.id !== fileToDelete))
      showMessage('success', '文件删除成功', {
        position: 'top-right',
        autoClose: 3000
      })
    } catch (error) {
      console.error('删除文件失败:', error)
      showMessage('error', '删除文件失败', {
        position: 'top-right',
        autoClose: 3000
      })
    } finally {
      setIsDeleteModalOpen(false)
      setFileToDelete(null)
      setFileToDeleteName('')
    }
  }

  const cancelDeleteFile = () => {
    setIsDeleteModalOpen(false)
    setFileToDelete(null)
    setFileToDeleteName('')
  }

  // 处理选择已有附件 - 立即复制并上传
  const handleSelectExistingAttachments = async (selectedAttachments: Attachment[]) => {
    // 检查重复：过滤掉与当前列表中同名且同类型的文件
    const existingFileKeys = new Set(
      attachments.map(att => `${att.name}|${att.type}`)
    )
    
    const uniqueAttachments = selectedAttachments.filter(att => {
      const fileKey = `${att.name}|${att.type}`
      return !existingFileKeys.has(fileKey)
    })
    
    // 如果有重复文件，给用户提示
    const duplicateCount = selectedAttachments.length - uniqueAttachments.length
    if (duplicateCount > 0) {
      const duplicateNames = selectedAttachments
        .filter(att => existingFileKeys.has(`${att.name}|${att.type}`))
        .map(att => att.name)
        .slice(0, 3) // 最多显示3个
      
      const message = duplicateCount <= 3
        ? `${duplicateNames.join('、')} 已存在，已自动跳过`
        : `${duplicateNames.join('、')} 等 ${duplicateCount} 个文件已存在，已自动跳过`
      
      showMessage('warning', message, {
        position: 'top-right',
        autoClose: 4000
      })
    }
    
    // 如果没有可添加的附件，直接返回
    if (uniqueAttachments.length === 0) {
      return
    }
    
    // 检查是否会超过限制
    const remainingSlots = Math.max(0, MAX_ATTACHMENTS - attachments.length - uploadingItems.length)
    if (uniqueAttachments.length > remainingSlots) {
      showMessage('warning', `当前附件列表已有 ${attachments.length} 个，最多只能再添加 ${MAX_ATTACHMENTS - attachments.length} 个附件`, {
        position: 'top-right',
        autoClose: 3000
      })
      return
    }

    const copiedAttachments: Attachment[] = []
    
    try {
      // 逐个复制附件，显示上传进度
      for (const attachment of uniqueAttachments) {
        const tempId = `${Date.now()}-${Math.random()}`
        
        try {
          // 加入上传队列（显示复制进度）
          setUploadingItems(prev => [...prev, { id: tempId, name: attachment.name }])
          
          // 调用后端接口复制附件
          const [copiedAttachment] = await copyExistingAttachments(complianceItemId, [attachment.id])
          
          if (copiedAttachment) {
            copiedAttachments.push(copiedAttachment)
          }
          
          // 延迟显示进度，提供更好的用户体验
          await new Promise(resolve => setTimeout(resolve, 500))
        } finally {
          // 移除该条上传任务
          setUploadingItems(prev => prev.filter(item => item.id !== tempId))
        }
      }
      
      // 更新附件列表
      if (copiedAttachments.length > 0) {
        console.log('attachments', attachments)
        console.log('copiedAttachments', copiedAttachments)
        onAttachmentsChange([...attachments, ...copiedAttachments])
        showMessage('success', `成功复制 ${copiedAttachments.length} 个附件`, {
          position: 'top-right',
          autoClose: 3000
        })
      }
    } catch (error) {
      console.error('复制附件失败:', error)
      const errorMessage = error instanceof AxiosError 
        ? error.message || '复制附件失败'
        : '复制附件失败'
      showMessage('error', errorMessage, {
        position: 'top-right',
        autoClose: 3000
      })
    }
  }

  return (
    <>
      {/* 全屏上传遮罩与队列（阻止交互） */}
      {uploadingItems.length > 0 && (
        <div className="fixed inset-0 z-50">
          <div className="absolute inset-0 bg-black/40 backdrop-blur-[1px]" />
          <div className="relative z-10 flex min-h-full items-start sm:items-center justify-center p-4">
            <div className="w-full max-w-md rounded-lg bg-white dark:bg-slate-900 shadow-lg ring-1 ring-black/5 p-4 space-y-3">
              <h3 className="text-sm font-medium text-zinc-800 dark:text-zinc-100">正在上传文件...</h3>
              <div className="space-y-3">
                {uploadingItems.map(item => (
                  <div key={item.id} className="space-y-1">
                    <div className="text-xs text-zinc-600 dark:text-zinc-300 truncate">{item.name}</div>
                    <ProgressBar indeterminate size="sm" />
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}

      <div className="mb-6">
        <label className="block text-sm font-medium text-gray-700 mb-2">附件</label>
        
        <div className="space-y-4">
          {/* 拖放区域 */}
          <div 
            className={`relative border-2 border-dashed rounded-lg p-6 text-center transition-colors ${
              isDragging 
                ? 'border-blue-500 bg-blue-50' 
                : 'border-gray-300 hover:border-blue-400'
            }`}
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
          >
            <div className="space-y-2">
              <Upload className="mx-auto h-10 w-10 text-gray-400" />
              <p className="text-sm text-gray-600">拖拽文件到此处或点击下方按钮选择文件</p>
              <p className="text-xs text-gray-500">(支持图片、PDF、Word、Excel等格式，一次最多可上传6个文件)</p>
            </div>
          </div>
          
          {/* 上传按钮组 */}
          <div className="grid grid-cols-2 gap-3">
            <button
              type="button"
              onClick={triggerFileInput}
              className="inline-flex justify-center items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
            >
              <Upload className="w-4 h-4 mr-2" />
              上传新文件
            </button>
            
            {assessmentPlanId && (
              <button
                type="button"
                onClick={() => setIsAttachmentSelectorOpen(true)}
                className="inline-flex justify-center items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
              >
                <FileSearch className="w-4 h-4 mr-2" />
                选择已有附件
              </button>
            )}
          </div>
          
          {/* 隐藏的文件输入 */}
          <input
            type="file"
            ref={fileInputRef}
            key={fileInputKey}
            onChange={handleFileInputChange}
            multiple
            className="hidden"
            accept="image/*,.pdf,.doc,.docx,.xls,.xlsx"
            aria-hidden="true"
          />
        </div>
        
        {/* 文件列表 */}
        {attachments && attachments.length > 0 && (
          <div className="mt-4 space-y-2">
            {attachments.map((file) => (
              <div key={file.id} className="group relative cursor-pointer" onClick={() => handleFileClick(file)}>
                <div className="flex items-center justify-between p-3 bg-gray-50 rounded-md hover:bg-gray-100">
                  <div className="flex items-center min-w-0 flex-1">
                    <div className="flex-shrink-0 h-10 w-10 rounded bg-blue-100 flex items-center justify-center text-blue-600">
                      {file.type && file.type.startsWith('image/') ? (
                        <img 
                          src={`${getBaseURL()}/attachments/${file.id}`} 
                          alt="" 
                          className="h-full w-full object-cover rounded"
                        />
                      ) : (
                        <span className="text-xs font-medium">
                          {file.name.split('.').pop()?.toUpperCase()}
                        </span>
                      )}
                    </div>
                    <div className="ml-3 min-w-0">
                      <p className="text-sm font-medium text-gray-900 truncate">{file.name}</p>
                      <p className="text-xs text-gray-500">
                        {file.size ? `${(file.size / 1024).toFixed(1)} KB` : '未知大小'}
                      </p>
                    </div>
                  </div>
                  <button
                    type="button"
                    onClick={(e) => { e.stopPropagation(); handleRemoveFile(file.id, file.name); }}
                    className="ml-2 p-1 text-gray-400 hover:text-red-500 rounded-full hover:bg-red-50 transition-colors"
                    aria-label={`删除文件 ${file.name}`}
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}

        {/* 删除确认弹窗 */}
        <DeleteConfirmModal
          isOpen={isDeleteModalOpen}
          onClose={cancelDeleteFile}
          onConfirm={confirmDeleteFile}
          itemName={fileToDeleteName}
          title="确认删除文件"
          message="您确定要删除以下文件吗？"
          dangerMessage="注意：此操作不可撤销，文件将被永久删除。"
          cancelText="取消"
          confirmText="删除文件"
        />

        {/* 已有附件选择器 */}
        {assessmentPlanId && (
          <ExistingAttachmentSelector
            isOpen={isAttachmentSelectorOpen}
            onClose={() => setIsAttachmentSelectorOpen(false)}
            onSelect={handleSelectExistingAttachments}
            assessmentPlanId={assessmentPlanId}
            currentAttachments={attachments}
          />
        )}
      </div>
    </>
  )
}

export default FileUploadSection
